<template>
  <div class="body_box">
    <!-- app-container -->
    <div class="head">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="" prop="query">
          <el-input style="width: 440px;" v-model="queryParams.query" placeholder="申请ID、关联单号、联系方式、卡编号、卡名称、第三方订单号"
            clearable />
        </el-form-item>
        <el-form-item label="退款类型：" prop="refundType">
          <el-select v-model="queryParams.refundType" filterable placeholder="请选择" clearable style="width: 200px" >
            <el-option v-for="dict in refundTypeList" :key="dict.id" :label="dict.value" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单来源：" prop="orderSource">
          <el-select v-model="queryParams.orderSource" placeholder="请选择" clearable style="width: 200px">
            <el-option v-for="dict in orderSourceLs" :key="dict.id" :label="dict.value" :value="dict.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="退款状态：" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" filterable clearable style="width: 200px" @change="changeStatus">
            <el-option v-for="dict in statusList" :key="dict.id" :label="dict.value" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款方式：" prop="refundWay">
          <el-select v-model="queryParams.refundWay" placeholder="请选择" filterable clearable style="width: 200px">
            <el-option v-for="dict in refundMethodList" :key="dict.id" :label="dict.value" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="">
          <el-dropdown split-button  style="margin-right:10px;" @command="handCommand">
                {{timeSatus==1?'申请时间':'操作时间'}}
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="1">申请时间</el-dropdown-item>
                  <el-dropdown-item :command="2">操作时间</el-dropdown-item>
              </el-dropdown-menu>
          </el-dropdown>
          <el-date-picker v-model="date" type="daterange" value-format="yyyy-MM-dd"  range-separator="至" 
              start-placeholder="开始日期" end-placeholder="结束日期" >
            </el-date-picker>
        </el-form-item>
        <el-form-item label="发行店铺：" prop="merchantId">
          <el-select v-model="queryParams.merchantId" placeholder="请选择" filterable clearable style="width: 200px">
            <el-option v-for="dict in merchantIdList" :key="dict.id" :label="dict.value" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery('queryForm')">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="listBox">
      <div class="main_top">
        <div class="lef">
          <div class="nav_list" v-for="item in typeList" :class="['list', currentNavtab == item.id ? 'active' : '']"
            :key="item.id" :value="item.id" @click="handleTab(item.id)">
            <span>{{ item.value }}</span>
          </div>
        </div>
        <div class="listBox_head">
          <el-button type="primary" @click="batchReviewView">批量审核</el-button>
          <el-button type="warning" @click="refundView">申请退款</el-button>
          <export-excel-button title="赚卡订单" action="/customer/equity/card/order/refund/v1/list/export"
            :params="ExportParams" />
        </div>
      </div>
      <el-table ref="table" v-loading="loading" :data="tabList" stripe border @selection-change="handleSelectAll"
        row-key="id" :header-cell-class-name="cellClass">
        <el-table-column type="selection" width="55" :selectable="selected"> </el-table-column>
        <el-table-column label="序号" align="center" type="index" width="64px" />
        <el-table-column label="申请ID" align="center" prop="applyId" :show-overflow-tooltip="true" width="180"/>
        <el-table-column label="申请时间" align="center" prop="applyTime" :show-overflow-tooltip="true" width="170"/>
        <el-table-column label="关联订单号" align="center" prop="orderNo" :show-overflow-tooltip="true" width="220"/>
        <el-table-column label="购买用户联系方式" align="center" prop="phone" :show-overflow-tooltip="true" width="120"/>

        <el-table-column label="卡编号" align="center" prop="cardNo" :show-overflow-tooltip="true" />
        <el-table-column label="卡名称" align="center" prop="cardName" :show-overflow-tooltip="true" />
        <el-table-column label="发行店铺" align="center" prop="shopName" :show-overflow-tooltip="true" width="150"/>
        <el-table-column label="订单来源" align="center" prop="orderSource" :show-overflow-tooltip="true" width="100" >
          <template slot-scope="scope">
            <dict-tag :options="orderSourceLs" :value="scope.row.orderSource" />
          </template>
        </el-table-column>
        <el-table-column label="第三方订单号" align="center" prop="thirdOrderNo" :show-overflow-tooltip="true" width="220"/>

        <el-table-column label="订单金额" align="center" prop="orderMoney" :show-overflow-tooltip="true" />
        <el-table-column label="退款金额" align="center" prop="refundMoney" :show-overflow-tooltip="true" />
        <el-table-column label="退款类型" align="center" prop="refundTypeDict" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="退款方式" align="center" prop="refundWayDict" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="状态" align="center" prop="statusDict" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作人" align="center" prop="operator" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作时间" align="center" prop="operatorTime" :show-overflow-tooltip="true" width="170"></el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="lookClick(scope.row)">查看</el-button>
            <el-button size="mini" type="text" @click="passClick(scope.row)" v-if="scope.row.status == 1">通过</el-button>
            <el-button size="mini" type="text" @click="turnClick(scope.row)" v-if="scope.row.status == 1">驳回</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList"></pagination>
    </div>
    <Dialog :row="rowData" v-bind="$attrs" v-if="dialogVisible" :visible.sync="dialogVisible" @success="_handleSuccess">
    </Dialog>
    <detailDialog :id="id" v-bind="$attrs" v-if="detailVisible" :visible.sync="detailVisible" @success="_handleSuccess">
    </detailDialog>
    <!-- 申请退款弹窗 -->
    <refundDialog v-if="refundVisible" :visible.sync="refundVisible" @success="_handleSuccess"></refundDialog>
    <!-- 批量退款弹窗 -->
    <batchReview v-if="batchVisible" :visible.sync="batchVisible" :selectTotalAmount="selectTotalAmount"  :selectIdList="selectIdList" @success="_handleSuccess"></batchReview>
  </div>
</template>
    
<script>
import {
  getList,
  refundAgree,
  merchantShopSelect,
  refundRefuse,
} from "@/api/syFundManagement/zhuanReturn";
import Dialog from "@/views/syFundManagement/zhuanReturn/components/dialog";
import detailDialog from "@/views/syFundManagement/zhuanReturn/components/detailDialog";
import refundDialog from "@/views/syFundManagement/zhuanReturn/components/refundDialog"
import batchReview from "@/views/syFundManagement/zhuanReturn/components/batchReview"
import ExportExcelButton from "@/components/ExportExcelButton/index";
import { date } from "jszip/lib/defaults";

export default {
  name: "",
  components: {
    Dialog,
    detailDialog,
    refundDialog,
    ExportExcelButton,
    batchReview
  },
  data() {
    return {
      exportLoading: false,
      dialogId: "",
      dialogVisible: false,
      detailVisible: false,
      refundVisible: false,
      batchVisible:false,
      // 遮罩层
      loading: false,
      // 导出遮罩层
      // 总条数
      total: 0,//状态字典数组
      //表格数据
      tabList: [],
      date: [],
      merchantList: [],//所属门店
      refundTypeList: [],
      typeList: [
        { id: '', value: '全部' },
        { id: '1', value: '待审核' },
        { id: '2', value: '已通过' },
        { id: '3', value: '已拒绝' },
        { id: '4', value: '已撤销' },
      ],
      statusList: [], //退款状态列表
      functionTypeList: [],
      pathType: "add",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        query: "", //卡查询
        refundType: '', //退款类型 1 全部退款 2 部分退款 customer_equity_card_order_refund_type
        status: '',//退款状态 1 待审核 2 已通过 3 已拒绝 4 已撤销 customer_equity_card_order_refund_status
        orderSource: '',//订单来源 customer_equity_card_order_source
        merchantId: '',//发行店铺id
        refundWay:'',//退款方式 退款方式 1 用户申请 2 手动申请 3 赚卡过期 customer_equity_card_order_refund_way
      },
      timeSatus:1, //时间类型选择 1 操作时间、2 申请时间
      currentNavtab: '',
      selectId: [],
      activeList: [
        { id: 1, value: '消费激励' },
        { id: 2, value: '同行助力' },
      ],
      rowData: {},
      id: '',
      orderSourceLs: [],//订单来源
      merchantIdList: [],//发行店铺
      refundMethodList:[],//退款方式列表
      selectIdList: [],//批量审核订单id
      selectTotalAmount:0,//退款总额
      selectDisabled:true, //是否关闭全选按钮
    };
  },
  computed: {
    ExportParams() {
      const params = {
        ...this.queryParams,
      };
      if(this.date.length > 0){
        if(this.timeSatus == 1){
          params.startDate = this.date[0]
          params.endDate = this.date[1]
        }else if(this.timeSatus == 2){
          params.operatorStartDate = this.date[0]
          params.operatorEndDate = this.date[1]
        }
      }
      return params;
    },
  },
  created() {
    if(this.$route.query.phone){
      this.queryParams.query = this.$route.query.phone;
    }
    this.getMerchantShopSelect();
    this.getStatusList()
    this.getList();
  },
  methods: {
    // 选择操作时间、申请时间事件
    handCommand(command){
       this.timeSatus = command
       console.log('command',command)
    },
    //获取发行店铺下拉列表
    getMerchantShopSelect() {
      merchantShopSelect().then(res => {
        this.merchantIdList = res.result
      })
    },
    // 获取活动状态字典
    getStatusList() {
      var dictType = "customer_equity_card_order_refund_type,customer_equity_card_order_refund_status,customer_equity_card_order_source,customer_equity_card_order_refund_way";
      this.$getSelectList(dictType)
        .then((res) => {
          this.refundTypeList = res.result[0].dictList
          this.statusList = res.result[1].dictList
          this.orderSourceLs = res.result[2].dictList
          this.refundMethodList = res.result[3].dictList//退款方式列表
        })
        .finally(() => { });
    },
    // 批量审核退款订单
    handleSelectAll(val) {
      console.log('val',val)
      var selList = []
      this.selectTotalAmount = 0
      val.forEach(item => {
        let obj = {
          customerEquityCardId: item.customerEquityCardId,
          customerId: item.customerId,
          orderId: item.orderId
        }
        selList.push(obj)
        this.selectTotalAmount = this.selectTotalAmount + item.payMoney
      });
      
      this.selectIdList = selList
      // this.queryParams.exportIdList = selList
    },
    // 批量审核
    batchReviewView() {
      if (this.selectIdList.length == 0) {
        this.$message.error('请勾选订单')
        return
      }else{
        this.selectTotalAmount = Math.round(this.selectTotalAmount * 100) / 100
        this.batchVisible = true
      }
    },
    /**
     * 全选按钮隐藏
     */
    cellClass(row) {
      // this.$refs.table.clearSelection();
      if (this.selectDisabled && row.columnIndex === 0) {
        return 'DisableSelection'
      }
    },
    // 选择置灰多选
    selected(row, index) {
      //  console.log('row',row)
      if (row.status == 1) { // 根据你的条件来设置
        return true //可选择
      } else {
        return false; //不可选择
      }
    },
    //获取所属门店下拉
    getMerchant() {
      shopSelect().then(res => {
        this.merchantList = res.result
      })
    },
    // 退款状态转变
    changeStatus(){
      // this.queryParams.status = id
      this.currentNavtab = this.queryParams.status
    },
    //切换选项
    handleTab(id) {
      this.queryParams.status = id
      this.queryParams.pageNum = 1
      this.currentNavtab = id;
      this.getList();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      let data = JSON.parse(JSON.stringify(this.queryParams));  //深拷贝
      if(this.date.length > 0){
        if(this.timeSatus == 1){
          data.startDate = this.date[0]
          data.endDate = this.date[1]
        }else if(this.timeSatus == 2){
          data.operatorStartDate = this.date[0]
          data.operatorEndDate = this.date[1]
        }
      }
      getList(data).then((response) => {
        response.result.records.forEach(item => {
          for (var key in item) {
            if (item[key] === '') {
              item[key] = "-";
            }
          }
        });
        this.tabList = response.result.records;
        // 判定是否显示多选按钮
        this.selectDisabled = true
        this.tabList.some(item=>{
          if(item.status == 1){
            this.selectDisabled = false
            return true
          }
        })
        this.total = response.result.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      };
      this.timeSatus = '1'
      this.currentNavtab = ''
      this.$refs["queryForm"].resetFields();
      this.date = []
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery(formName) {
      //创建确定
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.queryParams.pageNum = 1;
          this.getList();
        } else {
          console.log("error submit!!");
          return false;
        }
      });

    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.reset();
      // this.handleQuery();
    },
    //新增
    _handleSuccess(e) {
      //成功回调
      this.getList();
    },
    //申请退款按钮点击
    refundView() {
      this.refundVisible = true
    },
    passClick(row) {
      var title = ''
      if (row.orderSource == 5) {
        title = `确定要通过${row.applyId}的申请退款么？该订单来源为微信视频号，确认通过仅能修改当前订单状态，退款请前往视频号后台`
      } else {
        title = `确定要通过${row.applyId}的退款申请么？`
      }
      this.$confirm(title, '提示', {
        confirmButtonText: '同意',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var data = {
          customerEquityCardId: row.customerEquityCardId,
          customerId: row.customerId,
          orderId: row.orderId
        }
        refundAgree(data).then((response) => {
          this.getList()
          this.$message.success('操作成功')
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //驳回
    turnClick(row) {
      this.dialogVisible = true
      this.rowData = row
    },
    //查看
    lookClick(row) {
      this.detailVisible = true
      this.id = row.id
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-table .DisableSelection .cell .el-checkbox__inner{
  display: none;
}
.body_box {
  padding: 20px;
}

.head {
  box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 20px 0;
}

.listBox {
  box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 20px;
  margin-top: 10px;
}

.listBox_head {
  padding: 0 0 20px 0;
}

.el-dropdown {
  margin-left: 10px;
}

.main_top {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  font-size: 14px;
  color: #333;
  background: #fff;
  border-radius: 6px;
  margin-bottom: 10px;

  .lef {
    display: flex;
    justify-content: flex-start;
    border: 1px solid #dfe6ec;
    height: 43px;

    .list {
      height: 41px;
      text-align: center;
      line-height: 41px;
      width: 140px;
      text-align: center;
      border-right: 1px solid #dfe6ec;
      background: #fff;
      cursor: pointer;
    }

    .list:nth-last-child(1) {
      border: none;
    }

    .active {
      background: #1890ff;
      color: #fff;
    }
  }
}

.img_box {
  width: 100px;
  height: 80px;
  border-radius: 4px;
}
</style>
    